package top.ochiamalu.aioj.util;

import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

/**
 * IP地址转换工具类
 *
 * @author jiangjs
 */
@Slf4j
public class IP2RegionUtils {

    private static final String DB_PATH = "/xdb/ip2region.xdb";

    private static byte[] dbBytes;

    static {
    try (InputStream is = IP2RegionUtils.class.getResourceAsStream(DB_PATH)) {
        if (is != null) {
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            byte[] data = new byte[1024];
            int bytesRead;
            while ((bytesRead = is.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, bytesRead);
            }
            buffer.flush();
            dbBytes = buffer.toByteArray();
        }
    } catch (IOException e) {
        throw new RuntimeException("无法加载 ip2region.xdb 文件", e);
    }
}


    private IP2RegionUtils() {
        // 私有构造函数，防止实例化
    }

    /**
     * 获取Searcher实例
     */
    private static Searcher getSearcher() throws IOException {
        if (dbBytes == null) {
            throw new RuntimeException("ip2region.xdb 文件未能正确加载");
        }
        return Searcher.newWithBuffer(dbBytes);
    }

    /**
     * 根据ip地址返回国家、省、城市信息
     * 
     * @param ip IP地址
     * @return 地理位置信息
     */
    public static String changeIpToAddress(String ip) {
        Searcher searcher = null;
        try {
            searcher = getSearcher();
            return searcher.search(ip);
        } catch (Exception e) {
            log.error("IP地址查询失败: {}", ip, e);
            return "";
        } finally {
            try {
                if (Objects.nonNull(searcher)) {
                    searcher.close();
                }
            } catch (Exception e) {
                log.error("关闭Searcher失败", e);
            }
        }
    }
}
